using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FernUniHagen.CompilerExtension.DataStructures;
using FernUniHagen.CompilerExtension.Attributes;
using Roslyn.Compilers.CSharp;
using FernUniHagen.CompilerExtension.Functions;
using Roslyn.Compilers.Common;

namespace FernUniHagen.CompilerExtension.Converter.Block
{
    public class MultExpressionConverter : BlockNodeFactory
    {
        public override List<StatementSyntax> ConvertBlockNode()
        {
            var statementsToAdd = new List<StatementSyntax>();
            //this Binary Expression contains ^variable
            var binaryExpression = NodeToReplaceInBlock.ReferencedNode as BinaryExpressionSyntax;
            //this Binary Expression contains ^variable^ (the full statement. Use this for the replacement)
            var parentBinaryExpression = NodeToReplaceInBlock.ReferencedNode.Parent as BinaryExpressionSyntax;
          
            //take the right side of the statement ^rightSide
            var declaration = SemanticModel.FindDecleration(binaryExpression.Right as IdentifierNameSyntax);
            var rightSideMultiplicity = Utilities.GetMultiplicityAttribute(declaration);

            switch (rightSideMultiplicity)
            {
                case AttributeType.Any:
                    var rmult2Expression = Syntax.ParseExpression(string.Format("{0}.Count", binaryExpression.Right.ToString()));
                    StatementReplacements = new StatementReplacement<CommonSyntaxNode>(parentBinaryExpression, rmult2Expression);
                    break;
                case AttributeType.Option:
                    var rmult1Expression = Syntax.ParseExpression(string.Format("{0} == null ? 0 : 1", binaryExpression.Right.ToString()));
                    StatementReplacements = new StatementReplacement<CommonSyntaxNode>(parentBinaryExpression, rmult1Expression);
                    break;
                default:
                    StatementReplacements = new StatementReplacement<CommonSyntaxNode>(NodeToReplaceInBlock.ReferencedNode, NodeToReplaceInBlock.ReferencedNode);
                    break;
            }

            return statementsToAdd;
        }
    }
}
